/* eslint-disable consistent-return */
import { PureComponent } from 'react';
import Taro, { showToast, setStorageSync, hideHomeButton } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import UiInput from '@/components/UiInput';
import { hintUserBind } from '@/utils/authLogin';

import { doLogin } from './server';

import './style.<%= css %>';

class LoginPage extends PureComponent {
  componentDidMount() {
    hideHomeButton();
  }

  loginMsg = {
    phoneNumber: '',
    password: '',
  };

  // 记录输入
  inputRecord = (type) => (e) => {
    this.loginMsg[type] = e.detail.value.trim();
  };

  // 用户登录
  login = async () => {
    const { phoneNumber, password } = this.loginMsg;
    if (!phoneNumber || !password) {
      return showToast({
        title: '手机号和密码不能为空',
        icon: 'none',
      });
    }
    try {
      const user = await doLogin({
        phoneNum: phoneNumber,
        userPassword: password,
      });

      setStorageSync('user', { ...(user || {}), phoneNumber });

      // 检测并提示用户绑定小程序
      await hintUserBind();

      Taro.reLaunch({ url: '/pages/index/index' });
    } catch (e) {
      console.log(e);
    }
  };

  render() {
    return (
      <View className="login-page pt-60">
        <Text className="fs-48 fw-b ml-48 mt-60 pt-20">登录</Text>
        <View className="ml-40 mr-40 mt-40">
          <UiInput type="number" onInput={this.inputRecord('phoneNumber')} placeholder="请输入手机号" maxLength={11} />
          <UiInput
            password
            type="text"
            onInput={this.inputRecord('password')}
            placeholder="请输入密码"
            maxLength={20}
          />
          <Button onClick={this.login} className="login-btn bg-main-orange cl-white no-border">
            立即登录
          </Button>
        </View>
      </View>
    );
  }
}

export default LoginPage;
